//
//  NNImageEditController.swift
//  CommonTool
//
//  Created by tenroadshow on 12.1.22.
//

import UIKit


class NNImageEditController: NNBaseViewController {

    var showingImageView1: UIImageView!
    var showingImageView2: UIImageView!
    
    
    lazy var doneBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Done", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.backgroundColor = .random
        btn.addTarget(self, action: #selector(nextPage(sender:)), for: .touchUpInside)
        return btn
    }()
    
    public var edtingViews: [NNEditingImageView] = []
    private var originImage1: UIImage = UIImage()
    private var originImage2: UIImage = UIImage()
    
    convenience init(originImage1: UIImage, originImage2: UIImage) {
        self.init()
        self.originImage1 = originImage1
        self.originImage2 = originImage2
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        let imageItem = UIBarButtonItem(title: "图片", style: .done, target: self, action: #selector(addImageEditingView))
        let textItem = UIBarButtonItem(title: "文字", style: .done, target: self, action: #selector(addTextEdtingView))
        navigationItem.rightBarButtonItems = [imageItem, textItem]
        
        
        let image1Scale = originImage1.size.width / originImage1.size.height
        let image1W = view.bounds.size.width
        let image1H = image1W / image1Scale
        showingImageView1 = UIImageView(frame: CGRect(x: 0, y: 20, width: image1W, height: image1H))
        showingImageView1.clipsToBounds = true
        showingImageView1.image = originImage1
        showingImageView1.isUserInteractionEnabled = true
        view.addSubview(showingImageView1)
        
        let image2Scale = originImage2.size.width / originImage2.size.height
        let image2W = view.bounds.size.width
        let image2H = image2W / image2Scale
        showingImageView2 = UIImageView(frame: CGRect(x: 0, y: showingImageView1.frame.maxY + 20, width: image2W, height: image2H))
        showingImageView2.clipsToBounds = true
        showingImageView2.image = originImage2
        showingImageView2.isUserInteractionEnabled = true
        view.addSubview(showingImageView2)
        
        
        view.addSubview(doneBtn)
        doneBtn.snp.makeConstraints { make in
            make.top.equalTo(showingImageView2.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 50, height: 50))
        }
        
    }
    
    @objc func nextPage(sender: UIButton) {
        
        guard let image1 = combineImage() else { return }
        let controller = NNEditResultController(image1: image1, image2: image1)
        navigationController?.pushViewController(controller, animated: true)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        addKeyboardNotification()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        removeKeyboardNotification()
    }
    
    @objc func addImageEditingView() {
        let addTextView = NNAddTextView(delegate: self)
        addTextView.addToSuperView(targetView: showingImageView1, infoModel: NNAddInfoModel())
    }
    
    @objc func addTextEdtingView(){
//        let attributeText = NSAttributedString(string: "越努力\n越幸运", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red,
//                                                                     NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 30)])
//
//        let infoModel = NNEditingInfoModel()
//        infoModel.isContentImage = false
//        infoModel.originalText = attributeText
//        infoModel.scale = 1.5
//
//        let imageView = NNEditingImageView(infoModel: infoModel)
//        imageView.editingViewTapHandle = { [weak self] edtingView in
//            let isActive = edtingView.isActive
//            self?.unActiveAllEditingViews()
//            imageView.isActive = isActive
//
//            self?.showingImageView1.bringSubviewToFront(edtingView)
//        }
//        showingImageView1.addSubview(imageView)
//
//        edtingViews.append(imageView)
//        unActiveAllEditingViews()
//        imageView.isActive = true
    }
    
    func unActiveAllEditingViews() {
        edtingViews.forEach { $0.isActive = false }
    }
    
    func combineImage() -> UIImage? {
        showingImageView1.subviews.forEach { child in
            if let child = child as? NNAddTextView {
                child.updateEditingStatus(isEditing: false)
            }
        }
        UIGraphicsBeginImageContextWithOptions(showingImageView1.bounds.size, false, UIScreen.main.scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        showingImageView1.layer.render(in: context)
        var targetImage: UIImage? = nil
        if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
            targetImage = newImage
        }
        UIGraphicsEndImageContext()
        return targetImage
    }
}


extension NNImageEditController: NNAddTextViewDelegate {
    
    func shouldBeginEditing(addtextView: NNAddTextView) {
        if customInputView == nil {
            customInputView = NNInputView(frame: CGRect(x: 0, y: CC.screenH, width: CC.screenW, height: 74))
        }
        customInputView?.show(content: addtextView.infoModel.contentText, completeHandle: { contentText in
            addtextView.textDidChanged(contentText: contentText)
        })
    }
    
}

extension UIImage {
    
   static func createImage(attributeText: NSAttributedString, attributes: [NSAttributedString.Key: Any]) -> UIImage? {
        
       let size = attributeText.fitSizeFrom(targetSize: CGSize(width: UIScreen.main.bounds.width,
                                                               height: CGFloat.greatestFiniteMagnitude))
       
       UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
       let point = CGPoint(x: kControlWH, y: kControlWH)
       guard let context = UIGraphicsGetCurrentContext() else { return nil }

       attributeText.tn_draw(in: context,
                             withPosition: point,
                             andHeight: Float(size.width),
                             andWidth: Float(size.height))
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return image
       
    }
    
    
}


extension NSAttributedString {
    
    func fitSizeFrom(targetSize: CGSize) -> CGSize {
        if length == 0 { return .zero }
        let frameSetter = CTFramesetterCreateWithAttributedString(self)
        let size = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0, length), nil, targetSize, nil)
        return size
    }
    
    func draw(int context: CGContext?, position: CGPoint, size: CGSize) -> UIImage? {
        self.draw(in: CGRect(origin: .zero, size: size))
        let tempImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tempImage
    }
    
    
    
}
